package com.ea.common.util;

import cn.hutool.core.util.IdUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author NAME-L
 * @Description TODO
 * @className TokenUtil
 * @date 2022-12-22 00:14:01
 */
public class TokenUtil {
    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    private static final long EXPIRE_TIME = 20 * 60 * 1000;

    private static final String JWT_KEY = "ELEA";
    @Autowired
    private RedisUtil redisUtil;

    public static String tokenGenerator(Long adminId) {
        return generateToken(IdUtil.simpleUUID() ,adminId);
    }

    public static String generateToken(String params , Long adminId){
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Date startDate = new Date();
        //秘钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(JWT_KEY);
        Map<String,Object> header = new HashMap<>();
        header.put("typ","JWT");
        header.put("alg","HS256");
        String token = JWT.create()
                .withHeader(header)
                .withIssuer("ELEA")
                .withIssuedAt(startDate)
                .withExpiresAt(date)
                .withClaim("adminId", adminId)
                .withClaim("UUID", params)
                .sign(algorithm);
        return token;
    }


    /**
     * token校验
     * @param token
     * @return
     */
    public static boolean verify(String token){
        /**
         * @desc   验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_KEY);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }
    }

    /**
     * 获取当前登录用户的id
     * @param token
     * @return
     */
    public static Long getUserId(String token){
        DecodedJWT jwt = JWT.decode(token);
        Map<String, Claim> map = jwt.getClaims();
        Claim keySet = map.get("adminId");
        return keySet.asLong();
    }
}
